package com.jinhuhang.u2.myselfmodule.engine.bid.addbid;

import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.jinhuhang.u2.MyApplication;
import com.jinhuhang.u2.R;
import com.jinhuhang.u2.common.constant.Constant;
import com.jinhuhang.u2.common.mvp.activity.ZSimpleBaseActivity;
import com.jinhuhang.u2.entity.AddBidParamsBean;
import com.jinhuhang.u2.entity.BidBean;
import com.jinhuhang.u2.entity.UserSingleResult;
import com.jinhuhang.u2.myselfmodule.engine.bid.BidActivity;
import com.jinhuhang.u2.ui.BottomDialogManager;
import com.jinhuhang.u2.ui.itemview.AddbidView;
import com.jinhuhang.u2.util.http.HttpWrapperList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;

/**
 * Created by OnionMac on 17/9/18.
 */

public class AddBidActivity extends ZSimpleBaseActivity implements AddBidContract.View{

    @Bind(R.id.toolbar_back)
    ImageView mToolbarBack;
    @Bind(R.id.toolbar_name)
    TextView mToolbarName;
    @Bind(R.id.toolbar_right)
    TextView mToolbarRight;
    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.addbid_cb_open)
    CheckBox mAddbidCbOpen;
    @Bind(R.id.addbid_tv_rule)
    TextView mAddbidTvRule;
    @Bind(R.id.addbid_product)
    AddbidView mAddbidProduct;
    @Bind(R.id.addbid_san)
    AddbidView mAddbidSan;
    @Bind(R.id.addbid_rate_none)
    AddbidView mAddbidRateNone;
    @Bind(R.id.addbid_rate_five)
    AddbidView mAddbidRateFive;
    @Bind(R.id.addbid_rate_nine)
    AddbidView mAddbidRateNine;
    @Bind(R.id.addbid_rate_twelve)
    AddbidView mAddbidRateTwelve;
    @Bind(R.id.addbid_cb_rate_1)
    CheckBox mAddbidCbRate1;
    @Bind(R.id.addbid_edt_rate)
    EditText mAddbidEdtRate;
    @Bind(R.id.addbid_cb_rate_2)
    CheckBox mAddbidCbRate2;
    @Bind(R.id.addbid_month)
    AddbidView mAddbidMonth;

    private static final String PRODUCT = "1";
    private static final String SAN = "0";

    private static final String RATE_NONE = "0.00";
    private static final String RATE_FIVE = "5.00";
    private static final String RATE_NINE = "9.00";
    private static final String RATE_TWELVE= "12.00";

    private static final String RATE_CB1 = "cb1";
    private static final String RATE_CB2 = "cb2";

    private String mCurrentProduct;
    private String mCurrentRate;
    private String mCurrentRateCB;

    private Map<String,AddbidView> mProduct = new HashMap<>();
    private Map<String,AddbidView> mRate = new HashMap<>();
    private Map<String,CheckBox> mRateCheckbox = new HashMap<>();

    private BottomDialogManager mBottomDialogManager;

    private Map<String,String> mParams = new HashMap<>();

    private String mId;

    private AddBidContract.Presenter mPresenter;

    private ArrayList<String> mXiaParams = new ArrayList<>();
    private Map<String,String> mParamsMap = new HashMap<>();
    private Map<String,String> mParamsMonthMap = new HashMap<>();

    @Override
    protected void initView() {
        mToolbarBack.setOnClickListener(v -> finish());
        mToolbarName.setText("自动投标");

        mAddbidProduct.setType(PRODUCT);
        mAddbidSan.setType(SAN);
        mProduct.put(PRODUCT,mAddbidProduct);
        mProduct.put(SAN,mAddbidSan);

        mAddbidRateNone.setType(RATE_NONE);
        mAddbidRateFive.setType(RATE_FIVE);
        mAddbidRateNine.setType(RATE_NINE);
        mAddbidRateTwelve.setType(RATE_TWELVE);
        mRate.put(RATE_NONE,mAddbidRateNone);
        mRate.put(RATE_FIVE,mAddbidRateFive);
        mRate.put(RATE_NINE,mAddbidRateNine);
        mRate.put(RATE_TWELVE,mAddbidRateTwelve);

        mRateCheckbox.put(RATE_CB1,mAddbidCbRate1);
        mRateCheckbox.put(RATE_CB2,mAddbidCbRate2);

        mBottomDialogManager = new BottomDialogManager(this);
    }


    @Override
    protected void initData() {
        mPresenter.getAddBidParams(getUserId());
    }

    @Override
    public void onGetAddBidParamsResult(HttpWrapperList<AddBidParamsBean> o) {
        if(Constant.SUCCESS_CODE == o.getCode()){
            ArrayList<AddBidParamsBean> data = o.getData();
            for (int i = 0; i < data.size(); i++) {
                if(data.get(i).getCode().equals("time_limit_type_month")){
                    mXiaParams.add(data.get(i).getName());
                    mParamsMap.put(data.get(i).getName(),data.get(i).getValue());
                    mParamsMonthMap.put(data.get(i).getValue(),data.get(i).getName());
                }
            }

            mBottomDialogManager.setTitle("选择月数");
            mBottomDialogManager.setData(mXiaParams);

            echo();
        }
    }

    private void echo() {
        Intent intent = getIntent();

        int type = intent.getIntExtra(BidActivity.TYPE,0);
        if(BidActivity.ADD == type){
            /**
             * 新增
             */
        }else if(BidActivity.CHANGE == type){

            /**
             * 修改
             */
            String bid = intent.getStringExtra(BidActivity.DATA);
            BidBean bidBean = MyApplication.mGson.fromJson(bid, BidBean.class);
            mId = bidBean.getId();
            /**
             * 状态
             */
            mAddbidCbOpen.setChecked("0".equals(bidBean.getStatus()));
            /**
             * 项目
             */
            switch (bidBean.getBorrowType()){
                case "0":
                    mAddbidSan.setCheck(true);
                    break;
                case "1":
                    mAddbidProduct.setCheck(true);
                    break;
                case "0,1":
                    mAddbidProduct.setCheck(true);
                    mAddbidSan.setCheck(true);
                    break;
            }
            /**
             * 年利率
             */
            for (Map.Entry<String, AddbidView> rate : mRate.entrySet()) {
                if(rate.getKey().equals(bidBean.getApr())){
                    rate.getValue().performClick();
                }
            }
            /**
             * 投资金额
             */
            if("0".equals(bidBean.getTenderType())){
                mAddbidCbRate1.setChecked(true);
                mAddbidEdtRate.setText(bidBean.getAmount());
            }else{

            }
            /**
             * 投资期限
             */
            String month = mParamsMonthMap.get(bidBean.getTimeLimitTypeMonth());
            mAddbidMonth.setMonthEnable(month);
        }
    }

    @Override
    public void onAddBidResult(HttpWrapperList<UserSingleResult> o) {
        if(Constant.SUCCESS_CODE == o.code){
            /**
             * 成功
             */
            finish();
        }
    }

    @Override
    protected void initListener() {
        mBottomDialogManager.setOkListener(select -> {
            mAddbidMonth.setMonthEnable(select);
            mBottomDialogManager.dismiss();
        });
        for (Map.Entry<String, AddbidView> entry : mProduct.entrySet()) {
            if(entry.getValue().isCheck()){
                mCurrentProduct = entry.getKey();
            }
            setProductListener(entry.getValue(),entry.getKey());
        }
        for (Map.Entry<String, AddbidView> entry : mRate.entrySet()) {
            if(entry.getValue().isCheck()){
                mCurrentRate = entry.getKey();
            }
            setRateListener(entry.getValue(),entry.getKey());
        }

        for (Map.Entry<String, CheckBox> entry : mRateCheckbox.entrySet()) {
            if(entry.getValue().isChecked()){
                mCurrentRateCB = entry.getKey();
                entry.getValue().setEnabled(false);
            }
            setRateCbListener(entry.getValue(),entry.getKey());
        }

        mAddbidMonth.setOnClickListener(v -> {
            mBottomDialogManager.show();
        });

        mToolbarRight.setOnClickListener(v -> {

            /**
             * 提交所有的
             */
            mParams.put("id",mId==null?"":mId); //如果是新增 则为空串
            mParams.put("userId",getUserId());
            mParams.put("status",mAddbidCbOpen.isChecked()?"0":"1");

            String borrowType = null;
            if(mAddbidProduct.isCheck() && mAddbidSan.isCheck()){
                borrowType = "0,1";
            }else if(mAddbidProduct.isCheck()){
                borrowType = PRODUCT;
            }else if(mAddbidSan.isCheck()){
                borrowType = SAN;
            }

            mParams.put("borrowType",borrowType);

            if(mAddbidCbRate1.isChecked()){
                mParams.put("tenderType","0");
                String money = mAddbidEdtRate.getText().toString();
                Double moneyDouble = Double.parseDouble(money);
                if(moneyDouble != 0 && moneyDouble % 100 == 0){
                    mParams.put("amount",money);
                }else{
                    showMessage("金额比如大于等于100的整倍数");
                    return;
                }
            }else{
                mParams.put("tenderType","1");
            }

            for (Map.Entry<String, AddbidView> value : mRate.entrySet()) {
                if(value.getValue().isCheck()){
                    mParams.put("apr",value.getValue().getTypeValue());
                }
            }

            if(TextUtils.isEmpty(mAddbidMonth.getTypeValue())){
                showMessage("请选择投资期限");
                return;
            }else{
                mParams.put("timeLimitTypeMonth",mParamsMap.get(mAddbidMonth.getTypeValue()));
            }

            mPresenter.addBid(mParams);
        });
    }

    private void setRateCbListener(CheckBox value, String key) {
        value.setOnCheckedChangeListener((buttonView, isChecked) -> {
            value.setEnabled(false);
            CheckBox preCheckBox = mRateCheckbox.get(mCurrentRateCB);
            preCheckBox.setChecked(false);
            preCheckBox.setEnabled(true);
            mCurrentRateCB = key;
            if(mCurrentRateCB.equals(RATE_CB1)){
                mAddbidEdtRate.setEnabled(true);
            }else{
                mAddbidEdtRate.setText("");
                mAddbidEdtRate.setEnabled(false);
            }
        });
    }

    private void setProductListener(AddbidView value, String key) {
        value.setOnClickListener(v -> {
            boolean check = value.isCheck();
            if(check){
                /**
                 * 当前按下的规则 已经是选中 另一个也选择则可以取消
                 */
                if(key.equals(PRODUCT)){
                    if(mProduct.get(SAN).isCheck()){
                        value.setCheck(false);
                    }else{
                        showMessage("必须选择一个产品");
                    }
                }else{
                    if(mProduct.get(PRODUCT).isCheck()){
                        value.setCheck(false);
                    }else{
                        showMessage("必须选择一个产品");
                    }
                }
            }else{
                value.setCheck(true);
            }
        });
    }

    private void setRateListener(AddbidView value, String key) {
        value.setOnClickListener(v -> {
            if(mCurrentRate.equals(key)){
                return;
            }
            mRate.get(mCurrentRate).setCheck(false);
            mCurrentRate = key;
            value.setCheck(!value.isCheck());
        });
    }
    @Override
    protected void attachPre() {
        mPresenter = new AddBidPresenter(this,getCompositeSubscription());
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_addbid;
    }
}
